package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnTimeSelectListener;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.MoneyFormatUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.ui.adapter.GoodsShopButtonAdapter;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.model.RepoGoodsEntity;
import cn.mumzone.pos.model.RepoGoodsSpecEntity;
import cn.mumzone.pos.model.RepoListGoodsEntity;
import cn.mumzone.pos.ui.widgets.PosTimePickerView;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import cn.mumzone.pos.ui.widgets.shopping.AnimShopButton;
import cn.mumzone.pos.ui.widgets.util.StringSpanUtils;
import cn.mumzone.pos.util.GoodsUtil;
import cn.mumzone.pos.util.StockBatchHolder;

public class ACT_AddOrModifyBatch extends BaseActivity {

    public static final String KEY_ADD_BATCH = "key_add_batch";
    public static final String KEY_MODIFY_BATCH = "key_modify_batch";
    public static final String KEY_IS_UPDATE = "key_is_update";

    public static final int REQUEST_CODE_ADD = 100;
    public static final int REQUEST_CODE_UPDATE = 200;

    @BindView(R.id.tv_good_name)
    TextView tvGoodName;
    @BindView(R.id.tv_good_spec)
    TextView tvGoodSpec;
    @BindView(R.id.tv_produce_date)
    TextView tvProduceDate;
    @BindView(R.id.et_batch_number)
    EditText etBatchNumber;
    @BindView(R.id.v_modify_count)
    AnimShopButton vModifyCount;
    @BindView(R.id.tv_price)
    EditText tvPrice;

    private RepoListGoodsEntity mTargetBean;
    private RepoGoodsEntity mTargetBatchBean;
    private PosTimePickerView posTimePickerView;

    private AlertDialog modifyPriceDialog;
    private EditText etPrice;
    private PosKeyBoardView kbPrice;

    private boolean isUpdate;

    @Override
    protected void getBundleExtras(Bundle extras) {
        isUpdate = extras.getBoolean(KEY_IS_UPDATE);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        overridePendingTransition(R.anim.right_in, R.anim.right_out);
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.gravity = Gravity.END;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(params);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setFinishOnTouchOutside(true);
    }

    @Override
    protected void initEventAndData() {

        mTargetBean = StockBatchHolder.INSTANCE.getTargetBean();
        mTargetBatchBean = StockBatchHolder.INSTANCE.getTargetBatchBean();

        // 新增批次
        if (!isUpdate) {
            tvGoodName.setText(mTargetBean.getGoodsName());
            tvGoodSpec.setText(getFormatGoodsSpec(mTargetBean.getParameter()));
            tvProduceDate.setText("请选择生产日期");
            etBatchNumber.setText("");
            vModifyCount.setCount(1);
            tvPrice.setText("");
        }

        // 编辑已有批次
        if (isUpdate) {
            tvGoodName.setText(mTargetBatchBean.getName());
            tvGoodSpec.setText(getFormatGoodsSpec(mTargetBatchBean.getParameter()));
            tvProduceDate.setText(mTargetBatchBean.getDateInProduced());
            etBatchNumber.setText(mTargetBatchBean.getGoodsBatchNumber());
            vModifyCount.setCount(mTargetBatchBean.getSelectedCount());
            tvPrice.setText(String.format("%s", mTargetBatchBean.getInStockPrice()));
        }

        vModifyCount.setOnAddDelListener(new GoodsShopButtonAdapter(mContext) {
            @Override
            public void onInputAreaClicked() {
                super.onInputAreaClicked();
                GoodsUtil.showModifyCountDialog(mContext, new PosKeyBoardView.OnConfirmClickListener() {
                    @Override
                    public void onConfirmClick(String text) {
                        vModifyCount.setCount(Integer.parseInt(text));
                        vModifyCount.invalidate();
                    }
                });
            }
        });

        initTimePickerView();

        initModifyPriceDialog();

    }

    private void initModifyPriceDialog() {
        modifyPriceDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_modify_in_stock_price)
                .setDialogTitle("修改入库单价")
                .setDialogNoConfirm()
                .setWidthAndHeight(438, 467)
                .create();
        kbPrice = modifyPriceDialog.findViewById(R.id.kb_price);
        etPrice = modifyPriceDialog.findViewById(R.id.et_price);
        MoneyFormatUtil.setTextFilter(etPrice);
        kbPrice.attachTo(etPrice);
        etPrice.setFocusable(false);
        kbPrice.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                tvPrice.setText(String.format("%s", text));
                closeDialog(modifyPriceDialog);
            }
        });
    }

    private void initTimePickerView() {
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        int nowYear = endDate.get(Calendar.YEAR);
        startDate.set(nowYear - 2, 0, 1);
        posTimePickerView = new PosTimePickerView.PosTimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tvProduceDate.setText(String.format("%s",
                        AppDateUtil.getDateToString(date.getTime(), AppDateUtil.YYYY_MM_DD)));
            }
        }).isDialog(true).isCyclic(false).setOutSideCancelable(true)
                .setTitleText("选择时间")
                .setType(new boolean[]{true, true, true, false, false, false})
                .setDate(endDate)
                .setRangDate(startDate, endDate)
                .build();
    }

    @Override
    protected int getLayout() {
        return R.layout.act_modify_batch;
    }

    @OnClick({R.id.iv_finish, R.id.tv_produce_date, R.id.tv_price, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_finish:
                setResult(RESULT_CANCELED);
                finish();
                overridePendingTransition(R.anim.right_in, R.anim.right_out);
                break;
            case R.id.tv_produce_date:
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                posTimePickerView.setDate(calendar);
                posTimePickerView.show();
                break;
            case R.id.tv_price:
                etPrice.setText("");
                etPrice.setHint(!TextUtils.isEmpty(tvPrice.getText().toString()) ? tvPrice.getText().toString() : "0.0");
                showDialog(modifyPriceDialog);
                break;
            case R.id.tv_save:
                if (isAllInputFieldValid()) {
                    updateOriginDataThenFinish();
                }
                break;
        }
    }

    private boolean isAllInputFieldValid() {
        if ("请选择生产日期".equals(tvProduceDate.getText().toString())) {
            PosToast.INSTANCE.makeShortToast(this, tvProduceDate.getHint().toString());
            return false;
        }
        if (TextUtils.isEmpty(etBatchNumber.getText().toString())) {
            PosToast.INSTANCE.makeShortToast(this, etBatchNumber.getHint().toString());
            return false;
        }
        if (TextUtils.isEmpty(tvPrice.getText().toString())) {
            PosToast.INSTANCE.makeShortToast(this, tvPrice.getHint().toString());
            return false;
        }
        return true;
    }

    private void updateOriginDataThenFinish() {

        // 新增批次
        if (!isUpdate) {
            RepoGoodsEntity repoGoodsEntity = new RepoGoodsEntity();
            repoGoodsEntity.setId(mTargetBean.getGoodsId());
            repoGoodsEntity.setName(mTargetBean.getGoodsName());
            repoGoodsEntity.setParameter(mTargetBean.getParameter());
            repoGoodsEntity.setDateInProduced(tvProduceDate.getText().toString());
            repoGoodsEntity.setGoodsBatchNumber(etBatchNumber.getText().toString());
            repoGoodsEntity.setSelectedCount(vModifyCount.getCount());
            repoGoodsEntity.setInStockPrice(Double.parseDouble(StringUtils.isEmpty(tvPrice.getText().toString()) ?
                    "0.0" : tvPrice.getText().toString().trim()));
            repoGoodsEntity.setManuallyAdd(true);

            // 如果已经有同批次号的商品，那就覆盖而不是新增
            if (!isActuallyUpdate(repoGoodsEntity)) {
                mTargetBean.getGoodsBatch().add(repoGoodsEntity);
            }
        }

        // 编辑批次
        if (isUpdate) {
            mTargetBatchBean.setDateInProduced(tvProduceDate.getText().toString());
            mTargetBatchBean.setGoodsBatchNumber(etBatchNumber.getText().toString());
            mTargetBatchBean.setSelectedCount(vModifyCount.getCount());
            mTargetBatchBean.setInStockPrice(Double.parseDouble(tvPrice.getText().toString()));
            mTargetBatchBean.setManuallyAdd(true);
        }

        setResult(RESULT_OK);

        finish();
        overridePendingTransition(R.anim.right_in, R.anim.right_out);

//        StockBatchHolder.INSTANCE.resetBatchHolderData();

    }

    private boolean isActuallyUpdate(RepoGoodsEntity repoGoodsEntity) {
        for (RepoGoodsEntity batchListEntity : mTargetBean.getGoodsBatch()) {
            if (repoGoodsEntity.getGoodsBatchNumber().equals(batchListEntity.getGoodsBatchNumber())) {
                batchListEntity.setSelectedCount(repoGoodsEntity.getSelectedCount());
                batchListEntity.setDateInProduced(repoGoodsEntity.getDateInProduced());
                batchListEntity.setInStockPrice(repoGoodsEntity.getInStockPrice());
                return true;
            }
        }
        return false;
    }

    public static void startActForAdd(Activity activity) {
        Intent intent = new Intent(activity, ACT_AddOrModifyBatch.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putBoolean(KEY_IS_UPDATE, false);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, REQUEST_CODE_ADD);
    }

    public static void startActForUpdate(Activity activity) {
        Intent intent = new Intent(activity, ACT_AddOrModifyBatch.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putBoolean(KEY_IS_UPDATE, true);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, REQUEST_CODE_UPDATE);
    }

    private String getFormatGoodsSpec(List<RepoGoodsSpecEntity> goodsSpec) {
        StringBuilder builder = new StringBuilder();
        if (!ListUtil.isListEmpty(goodsSpec)) {
            for (int index = 0; index < goodsSpec.size(); index++) {
                RepoGoodsSpecEntity specBean = goodsSpec.get(index);
                builder.append(specBean.getParamValue());
                if (index < goodsSpec.size() - 1) {
                    builder.append("，");
                }
            }
        }
        return StringSpanUtils.init().addForegroundColorHighLight(mContext.getResources().getColor(R.color.weak_text_color), "规格：")
                .addStr(StringUtils.get(builder.toString(), "无")).build().toString();
    }

}
